
from flask import Flask

from datareport.api import ConfigClass
from datareport.api.IApplication import IApplication
from datareport.restful.downloadrestful import controller

app=Flask('三会一课报告')
app.register_blueprint(controller)
body=[]
class Application(IApplication):

    def run(self,context):

        import importlib
        import os
        from datareport.impl.paragraph.base.BaseParagraph import BaseParagraph

        ConfigClass.setData(context)
        pkg_path=context['pkg_path']
        body_list = os.listdir(f'{pkg_path}/impl/paragraph/body')
        # footer_list = os.listdir('datareport/impl/paragraph/footer')
        _body: [BaseParagraph] = []
        from pathlib import Path
        package = Path(pkg_path).stem
        print('当前背包{}'.format(package))
        for impl_name in body_list:
            if not impl_name.endswith('.py'):
                continue
            module_name = impl_name.split(".py")[0]
            if int(module_name.split('_')[-1])<54:
                module = importlib.import_module(f"{package}.impl.paragraph.body.{module_name}")
                try:
                    _body.append(getattr(module, module_name))
                except AttributeError as e:
                    # 自定义异常信息
                    print(f"Failed to get attribute {module_name} from module {module}.")
                    # 利用 raise 语句重新引发异常，将其抛出
                    continue
        ## 按照顺序排列文本
        _body = sorted(_body, key=lambda ob: int(ob().__class__.__name__.split('_')[-1]))
        global body
        body=_body

        from gevent import pywsgi
        server = pywsgi.WSGIServer(('0.0.0.0', 5000), app)
        print(f"Serving http on port 5000")
        print('启动成功')
        server.serve_forever()
        # app.run(host='0.0.0.0', port=8080)

    def start(self,context):
        from datareport.impl.BodyWriter import BodyWriter
        from datareport.impl.paragraph.base import BaseParagraph
        from docx import Document
        from datareport.api.DataSource import DataSource

        doc = Document()
        docw = BodyWriter(doc)
        conn = DataSource(context['datasource']).conn
        conn1 = DataSource(context['datasource1']).conn
        # """图像全局设置"""
        import matplotlib.pyplot as plt
        global body
        for ob in body:
            t: BaseParagraph = ob()
            t.start(conn,context['year'], plt)
            docw.writer(t)

        conn.close()

        """
        下载文件
        """
        from datareport.api.DocxFileUtil import download
        return download(doc, context)

